package com.ecube.maintenance.components.fragment;


import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ecube.maintenance.R;
import com.ecube.maintenance.biz.commons.Constants;
import com.ecube.maintenance.components.application.CCBApplication;
import com.ecube.maintenance.pojos.UserInfo;
import com.ecube.maintenance.utils.Bog;
import com.ecube.maintenance.utils.ImageUtil;
import com.makeramen.RoundedImageView;

import java.io.File;


/**
 * Fragment used for managing interactions for and presentation of a navigation drawer.
 * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
 * design guidelines</a> for a complete explanation of the behaviors implemented here.
 */
public class NavigationDrawerFragment extends Fragment {

    /**
     * Remember the position of the selected item.
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * Per the design guidelines, you should show the drawer on launch until the user manually
     * expands it. This shared preference tracks this.
     */
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

    /**
     * A pointer to the current callbacks instance (the Activity).
     */
    private NavigationDrawerCallbacks mCallbacks;

    /**
     * Helper component that ties the action bar to the navigation drawer.
     */
    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mDrawerLayout;
    private LinearLayout mDrawerLayoutView;
    private View mFragmentContainerView;
    private int mCurrentSelectedPosition = 0;
    private boolean mFromSavedInstanceState;
    private boolean mUserLearnedDrawer;
    private boolean mUserLogin;
    private NavigationListAdapter mNavigationListAdapter;
    private RoundedImageView userAvatar;
    private TextView userCarNO;

    public NavigationDrawerFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Read in the flag indicating whether or not the user has demonstrated awareness of the
        // drawer. See PREF_USER_LEARNED_DRAWER for details.
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
        //TODO
        mUserLogin = isLogin();
        if (savedInstanceState != null) {
            mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
            mFromSavedInstanceState = true;
        }
        selectItem(mCurrentSelectedPosition);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(false);

    }

    @Override
    public void onResume() {
        super.onResume();
        configureActionBar();
    }

    private void configureActionBar() {
        ActionBar actionBar = getActivity().getActionBar();
        assert actionBar != null;
        View v = actionBar.getCustomView();
        if (v != null) {
            v.setVisibility(View.GONE);
        }
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle("车型选择");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mDrawerLayoutView = (LinearLayout) inflater.inflate(
                R.layout.fragment_navigation_drawer, container, false);
        ListView mListView = (ListView) mDrawerLayoutView.findViewById(R.id.drawer_list);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItem(position);
            }
        });
        userAvatar = (RoundedImageView) mDrawerLayoutView.findViewById(R.id.nav_ui_avatar);
        userCarNO = (TextView) mDrawerLayoutView.findViewById(R.id.CarNO);
        refreshUserHead();

        mNavigationListAdapter = new NavigationListAdapter(getActivity());
        mListView.setAdapter(mNavigationListAdapter);
        return mDrawerLayoutView;
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    }

    public void refreshUserHead() {
        UserInfo ui = UserInfo.getInstance();
        userAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!UserInfo.isLogin()) {
                    Bog.toast("请先登录.");
                    return;
                }
                if (mDrawerLayout != null) {
                    mDrawerLayout.closeDrawer(mFragmentContainerView);
                }
                FragmentTransaction ft = getFragmentManager().beginTransaction()
                        .setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
                ft.replace(R.id.container, UserInfoFragment.newInstance()).addToBackStack(null).commit();
            }
        });
        if (!UserInfo.isLogin()) {
            userAvatar.setImageResource(R.drawable.icon_account_no_picture);
            userCarNO.setText("");
        } else {
            userCarNO.setText(ui.getCarNO());
            String url = UserInfo.getInstance().getLogo();
            if (url == null) return;
            Bitmap bm = ImageUtil.getScaleOptionImageByScaleOfWinWidth(
                    getActivity(), new File(url), 0.5f
            );
            if (bm != null) {
                userAvatar.setImageBitmap(bm);
            }

        }

    }
    public String getVersion() {
         try {
                 Activity activity = getActivity();
                 PackageManager manager = activity.getPackageManager();
                 PackageInfo info = manager.getPackageInfo(activity.getPackageName(), 0);
                 String version = "("+info.versionName+")" ;
                 return version;
             } catch (Exception e) {
                e.printStackTrace();
                return "";
             }
    }
    private void selectItem(int position) {
        mCurrentSelectedPosition = position;
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        if (mCallbacks != null) {
            mCallbacks.onNavigationDrawerItemSelected(position);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (NavigationDrawerCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if (mDrawerLayout != null && isDrawerOpen()) {
            inflater.inflate(R.menu.main, menu);
        }
        super.onCreateOptionsMenu(menu, inflater);
        getActivity().invalidateOptionsMenu();
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        if (mDrawerLayout != null && isDrawerOpen()) {
            menu.clear();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    public void notifyDataChange() {
        mUserLogin = isLogin();
        this.mNavigationListAdapter.notifyDataSetChanged();
        refreshUserHead();
    }

    public boolean isLogin() {
        if (UserInfo.getInstance().getSid() != null)
            return true;
        else
            return false;
    }

    private ActionBar getActionBar() {
        return getActivity().getActionBar();
    }

    public static interface NavigationDrawerCallbacks {

        void onNavigationDrawerItemSelected(int position);
    }

    private class NavigationListAdapter extends BaseAdapter {
        String[] title = getResources().getStringArray(R.array.title_drawer_item);
        int[] imgId = new int[]{R.drawable.ic_sp, R.drawable.ic_order,
                R.drawable.ic_car, R.drawable.ic_star, 0, 0, 0, 0};
        boolean[] hasDivider = new boolean[]{false, true, false, true, false, false, false, false};
        private LayoutInflater inflater;

        public NavigationListAdapter(Context context) {
            this.inflater = LayoutInflater.from(context);
            title[4]+=getVersion();
        }

        @Override
        public int getCount() {
            return title.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            mUserLogin = UserInfo.isLogin();
            if (!mUserLogin && position >= 1 && position <= 3) {
                if (position == 2) {
                    convertView = this.inflater.inflate(R.layout.item_list_drawer_reg, null);
                    convertView.findViewById(R.id.item_drawer_image)
                            .setOnLongClickListener(new View.OnLongClickListener() {
                                @Override
                                public boolean onLongClick(View view) {
                                    if(Constants.DEBUG_MODE){
                                        //后门用于切换本地与服务器
//                                    ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(200);
//                                    Constants.DEBUG_MODE = !Constants.DEBUG_MODE;
                                    }
                                    return false;
                                }
                            });
                    convertView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getFragmentManager().beginTransaction()
                                    .replace(R.id.container, LoginFragment.newInstance())
                                    .addToBackStack("LF").commit();
                            mDrawerLayout.closeDrawer(mFragmentContainerView);
                        }
                    });
                } else convertView = new View(getActivity());
                return convertView;
            }
            //TODO 暂时取消收藏功能
            if (position == 3) return new View(getActivity());
            if (position == 7 && !mUserLogin) return new View(getActivity());

            final ViewHolder holder;
            if (convertView == null || convertView.getId() != R.id.item_list_drawer) {
                holder = new ViewHolder();
                convertView = this.inflater.inflate(R.layout.item_list_drawer, null);
                holder.iv = (ImageView) convertView.findViewById(R.id.item_drawer_image);
                holder.tv = (TextView) convertView.findViewById(R.id.item_drawer_text);
                holder.dv = convertView.findViewById(R.id.item_drawer_divider);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (imgId[position] != 0)
                holder.iv.setImageResource(imgId[position]);
            if (position < 4) {
                holder.tv.setTextSize(16);
                holder.tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            }

            holder.tv.setText(title[position]);
            if (hasDivider[position]) holder.dv.setVisibility(View.VISIBLE);
            return convertView;
        }

        public class ViewHolder {
            TextView tv;
            ImageView iv;
            View dv;
        }
    }
}
